package org.myapp.page.login.form;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.validator.StringValidator;

import org.myapp.page.validator.AlphaNurmericValidator;

/**
 * ユーザ登録フォーム.<br>
 *
 * @author Administrator
 *
 */
public class RegistForm extends BaseForm<LoginFormModel> {

    private static final long serialVersionUID = -288357181993763945L;

    private final PasswordTextField password2 = new PasswordTextField("txtPassword2");

    /**
     * コンストラクタ.<br>
     */
    public RegistForm(LoginFormModel model) {
        super("usRegistForm", model);

        setModel(new CompoundPropertyModel<LoginFormModel>(model));

        // Validator
        password2.add(StringValidator.minimumLength(6));
        password2.add(new AlphaNurmericValidator());

        add(password2);

        // FormValidator(相関)
        add(new AbstractFormValidator() {

            private static final long serialVersionUID = 1L;

            @Override
            public void validate(Form<?> arg0) {

                String userId = getUserId().getConvertedInput();
                String password1 = getPassword().getConvertedInput();
                String password2 = getPassword2().getConvertedInput();

                // ユーザが存在するか
                if (getLoginService().existUser(userId)) {
                    error(getUserId(), "registForm.existUserError");
                    return;
                }

                // パスワードは一致しているか
                if (!password1.equals(password2)) {
                    error(getPassword(), "registForm.equalPassError");
                    return;
                }
            }

            @Override
            public FormComponent<?>[] getDependentFormComponents() {
                return new FormComponent[] {getUserId(), getPassword(), getPassword2()};
            }
        });

        add(new Button("btnUsRegist") {

            private static final long serialVersionUID = -6875006625305861010L;

            public void onSubmit() {

                LoginFormModel form = getFormModel();

                // ユーザ登録
                getLoginService().registUser(form.getTxtUserId(), form.getTxtPassword1());

                info(this.getLocalizer().getString("msg.info.2", getPage()));
            };
        });
    }

    public PasswordTextField getPassword2() {
        return password2;
    }
}
